package com.cdp.web.controller.system;

import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysDeformationPerformance;
import com.cdp.common.core.domain.entity.SysDurabilityPerformance;
import com.cdp.common.core.domain.entity.SysMechanicalPerformance;
import com.cdp.system.dto.DeformationPerformanceDTO;
import com.cdp.system.dto.ExportDeformationPerformanceExcelDTO;
import com.cdp.system.dto.ExportDurabilityPerformanceExcelDTO;
import com.cdp.system.dto.ExportMechanicalPerformanceExcelDTO;
import com.cdp.system.service.ISysDeformationPerformanceService;
import com.cdp.system.service.ISysDurabilityPerformanceService;
import com.cdp.system.vo.DeformationPerformanceVO;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * deformation
 * 变形性能
 */
@RestController
@RequestMapping("/system/deformation")
public class SysDeformationPerformanceController {


    @Autowired
    private ISysDeformationPerformanceService sysDeformationPerformanceService;

    @Autowired
    private ISysDurabilityPerformanceService sysDurabilityPerformanceService;

    /**
     * 查询
     * 变形性能
     *
     * @return
     */
    @GetMapping("listDeformationPerformance")
    public AjaxResult listDeformationPerformance() {
        List<SysDeformationPerformance> listedDeformationPerformance = sysDeformationPerformanceService.listDeformationPerformance();
        return AjaxResult.success(listedDeformationPerformance);
    }

    /**
     * 查询变形性能数据
     *
     * @param deformationPerformanceDTO 查询条件
     * @return AjaxResult 包含查询结果
     */
    @PostMapping("/queryMistedDeformationPerformance")
    public AjaxResult queryMistedDeformationPerformance(@RequestBody DeformationPerformanceDTO deformationPerformanceDTO) {
        // 调用服务层查询并返回 VO 对象
        List<DeformationPerformanceVO> voList = sysDeformationPerformanceService.queryDeformationPerformance(deformationPerformanceDTO);

        // 返回结果
        return AjaxResult.success(voList);
    }


    /**
     * 变形性能导出excel
     */

    @PostMapping("exportMistedDeformationPerformanceExcelText")
    public AjaxResult exportMistedDeformationPerformanceExcelText(@RequestBody ExportDeformationPerformanceExcelDTO exportDeformationPerformanceExcelDTO) {

        List<SysDeformationPerformance> sysDeformationPerformanceList = sysDeformationPerformanceService.exportMistedDeformationPerformanceExcelText(exportDeformationPerformanceExcelDTO);

        return AjaxResult.success(sysDeformationPerformanceList);
    }


    /**
     * 导出excel
     *
     * @param
     * @return
     */

    @PostMapping("exportMistedDeformationPerformanceExcel")
    public ResponseEntity<byte[]> exportMistedDeformationPerformanceExcel(@RequestBody ExportDeformationPerformanceExcelDTO exportDeformationPerformanceExcelDTO) throws IOException, UnsupportedEncodingException {
        // 获取各类原材料的 ID 列表

        List<SysDeformationPerformance> sysDeformationPerformanceList = sysDeformationPerformanceService.exportMistedDeformationPerformanceExcelText(exportDeformationPerformanceExcelDTO);

        // 创建一个 Excel 工作簿
        Workbook workbook = new XSSFWorkbook();
        createMistedDeformationPerformanceSheet(workbook, sysDeformationPerformanceList);

        // 将 Excel 数据写入字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        byteArrayOutputStream.close();

        byte[] excelData = byteArrayOutputStream.toByteArray();
        String fileName = "变形性能数据.xlsx";

        // 对文件名进行 URL 编码
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 设置响应头，返回 Excel 文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + encodedFileName);
        headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .body(excelData);
    }


    private void createMistedDeformationPerformanceSheet(Workbook workbook, List<SysDeformationPerformance> sysDeformationPerformanceList) {
        // 创建一个名为 "变形性能" 的工作表
        Sheet sheet = workbook.createSheet("变形性能");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("变形性能ID");
        headerRow.createCell(1).setCellValue("7天自收缩 (%)");
        headerRow.createCell(2).setCellValue("28天自收缩 (%)");
        headerRow.createCell(3).setCellValue("地区名称");
        headerRow.createCell(4).setCellValue("水用量 (kg/m³)");
        headerRow.createCell(5).setCellValue("水泥ID");
        headerRow.createCell(6).setCellValue("水泥用量 (kg/m³)");
        headerRow.createCell(7).setCellValue("砂ID");
        headerRow.createCell(8).setCellValue("砂用量 (kg/m³)");
        headerRow.createCell(9).setCellValue("石类型ID");
        headerRow.createCell(10).setCellValue("石用量 (kg/m³)");
        headerRow.createCell(11).setCellValue("减水剂ID");
        headerRow.createCell(12).setCellValue("减水剂掺量 (%)");
        headerRow.createCell(13).setCellValue("增效剂ID");
        headerRow.createCell(14).setCellValue("增效剂掺量 (%)");
        headerRow.createCell(15).setCellValue("粉煤灰ID");
        headerRow.createCell(16).setCellValue("粉煤灰用量 (kg/m³)");
        // 填充数据
        int rowNum = 1;
        for (SysDeformationPerformance performance : sysDeformationPerformanceList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(safeToString(performance.getDeformationId()));          // 变形性能ID
            row.createCell(1).setCellValue(safeToString(performance.getShrinkage7d()));            // 7天自收缩
            row.createCell(2).setCellValue(safeToString(performance.getShrinkage28d()));           // 28天自收缩
            row.createCell(3).setCellValue(safeToString(performance.getRegionNameStr()));          // 地区名称
            row.createCell(4).setCellValue(safeToString(performance.getWaterContent()));           // 水用量
            row.createCell(5).setCellValue(safeToString(performance.getCementId()));               // 水泥ID
            row.createCell(6).setCellValue(safeToString(performance.getCementContent()));          // 水泥用量
            row.createCell(7).setCellValue(safeToString(performance.getSandId()));                 // 砂ID
            row.createCell(8).setCellValue(safeToString(performance.getSandContent()));            // 砂用量
            row.createCell(9).setCellValue(safeToString(performance.getStoneId()));               // 石类型ID
            row.createCell(10).setCellValue(safeToString(performance.getStoneContent()));          // 石用量
            row.createCell(11).setCellValue(safeToString(performance.getReducerId()));             // 减水剂ID
            row.createCell(12).setCellValue(safeToString(performance.getWaterReducerDosage()));    // 减水剂掺量
            row.createCell(13).setCellValue(safeToString(performance.getAgentId()));               // 增效剂ID
            row.createCell(14).setCellValue(safeToString(performance.getEfficiencyAgentDosage())); // 增效剂掺量
            row.createCell(15).setCellValue(safeToString(performance.getFlyashId()));              // 粉煤灰ID
            row.createCell(16).setCellValue(safeToString(performance.getFlyAshContent()));          // 粉煤灰用量
        }
    }


    // 辅助方法：安全地将值转换为字符串
    private String safeToString(Object value) {
        return value == null ? "" : value.toString();
    }


    /**
     * 耐久性能导出excel
     */
    @PostMapping("exportDurabilityPerformanceExcelText")
    public AjaxResult exportDurabilityPerformanceExcelText(@RequestBody ExportDurabilityPerformanceExcelDTO exportDurabilityPerformanceExcelDTO) {
        List<Integer> durabilityIds = exportDurabilityPerformanceExcelDTO.getDurabilityIds();

        List<SysDurabilityPerformance> sysDurabilityPerformanceList =sysDurabilityPerformanceService.exportDurabilityPerformanceExcelText(durabilityIds);
        return AjaxResult.success(sysDurabilityPerformanceList);
    }


    /**
     * 耐久性能导出excel
     */
    @PostMapping("exportDurabilityPerformanceExcel")
    public ResponseEntity<byte[]> exportDurabilityPerformanceExcel(@RequestBody ExportDurabilityPerformanceExcelDTO exportDurabilityPerformanceExcelDTO) throws IOException, UnsupportedEncodingException {
        // 获取各类原材料的 ID 列表
        List<Integer> durabilityIds = exportDurabilityPerformanceExcelDTO.getDurabilityIds();

        List<SysDurabilityPerformance> sysDurabilityPerformanceList =sysDurabilityPerformanceService.exportDurabilityPerformanceExcelText(durabilityIds);

        // 创建一个 Excel 工作簿
        Workbook workbook = new XSSFWorkbook();
        createDurabilityPerformanceSheet(workbook, sysDurabilityPerformanceList);

        // 将 Excel 数据写入字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        byteArrayOutputStream.close();

        byte[] excelData = byteArrayOutputStream.toByteArray();
        String fileName = "耐久性能数据.xlsx";

        // 对文件名进行 URL 编码
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 设置响应头，返回 Excel 文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + encodedFileName);
        headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .body(excelData);
    }


    private void createDurabilityPerformanceSheet(Workbook workbook, List<SysDurabilityPerformance> sysDurabilityPerformanceList) {

        // 创建一个名为 "耐久性能" 的工作表
        Sheet sheet = workbook.createSheet("耐久性能");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("耐久性能ID");
        headerRow.createCell(1).setCellValue("抗冻等级");
        headerRow.createCell(2).setCellValue("抗渗等级");
        headerRow.createCell(3).setCellValue("碳化深度 (mm)");
        headerRow.createCell(4).setCellValue("地区名称");
        headerRow.createCell(5).setCellValue("水用量 (kg/m³)");
        headerRow.createCell(6).setCellValue("水泥ID");
        headerRow.createCell(7).setCellValue("水泥用量 (kg/m³)");
        headerRow.createCell(8).setCellValue("粉煤灰用量 (kg/m³)");
        headerRow.createCell(9).setCellValue("砂ID");
        headerRow.createCell(10).setCellValue("砂用量 (kg/m³)");
        headerRow.createCell(11).setCellValue("石类型ID");
        headerRow.createCell(12).setCellValue("石用量 (kg/m³)");
        headerRow.createCell(13).setCellValue("减水剂ID");
        headerRow.createCell(14).setCellValue("减水剂掺量 (%)");
        headerRow.createCell(15).setCellValue("增效剂ID");
        headerRow.createCell(16).setCellValue("增效剂掺量 (%)");


        // 填充数据
        int rowNum = 1;
        for (SysDurabilityPerformance performance : sysDurabilityPerformanceList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(safeToString(performance.getDurabilityId()));             // 耐久性能ID
            row.createCell(1).setCellValue(safeToString(performance.getFreezeResistanceLevel()));   // 抗冻等级
            row.createCell(2).setCellValue(safeToString(performance.getImpermeabilityLevel()));     // 抗渗等级
            row.createCell(3).setCellValue(safeToString(performance.getCarbonationDepth()));        // 碳化深度
            row.createCell(4).setCellValue(safeToString(performance.getRegionNameStr()));           // 地区名称
            row.createCell(5).setCellValue(safeToString(performance.getWaterContent()));            // 水用量
            row.createCell(6).setCellValue(safeToString(performance.getCementId()));                // 水泥ID
            row.createCell(7).setCellValue(safeToString(performance.getCementContent()));           // 水泥用量
            row.createCell(8).setCellValue(safeToString(performance.getFlyAshContent()));           // 粉煤灰用量
            row.createCell(9).setCellValue(safeToString(performance.getSandId()));                  // 砂ID
            row.createCell(10).setCellValue(safeToString(performance.getSandContent()));            // 砂用量
            row.createCell(11).setCellValue(safeToString(performance.getStoneId()));                // 石类型ID
            row.createCell(12).setCellValue(safeToString(performance.getStoneContent()));           // 石用量
            row.createCell(13).setCellValue(safeToString(performance.getReducerId()));              // 减水剂ID
            row.createCell(14).setCellValue(safeToString(performance.getWaterReducerDosage()));     // 减水剂掺量
            row.createCell(15).setCellValue(safeToString(performance.getAgentId()));                // 增效剂ID
            row.createCell(16).setCellValue(safeToString(performance.getEfficiencyAgentDosage()));  // 增效剂掺量

        }
    }




}









